package com.banding.sort;

public class MergeSort {
    public static void sort(int[] nums) {
        sort(nums, 0, nums.length - 1);
    }

    public static void sort(int[] nums, int start, int end) {
        if (start >= end) {
            return;
        }
        int mid = (start + end) / 2;
        sort(nums, start, mid);
        sort(nums, mid + 1, end);
        merge(nums, start, mid, end);
//        System.out.println(StrUtil.format("sort({},{},{})",nums, start, mid));
//        System.out.println(StrUtil.format("sort({},{},{})",nums, mid + 1, end));
//        System.out.println(StrUtil.format("merge({},{},{},{})",nums, start, mid, end));
    }

    private static void merge(int[] nums, int start, int mid, int end) {
        int[] result = new int[end - start + 1];
        // i 为第一部分起点 ， j 为第二部分起点 ， k 为临时数组索引
        int i = start;
        int j = mid + 1;
        int k = 0;
        while (i <= mid && j <= end) {
            if (nums[i] < nums[j]) {
                result[k++] = nums[i++];
            } else {
                result[k++] = nums[j++];
            }
        }

        while (i <= mid) {
            result[k++] = nums[i++];
        }
        while (j <= end) {
            result[k++] = nums[j++];
        }
        System.arraycopy(result, 0, nums, start, result.length);
    }


}
